<template>
  <!-- Simple 模式：使用 select 类型 -->
  <ToolbarButton
    v-if="actualMode === 'simple'"
    type="select"
    :model-value="currentHeading"
    :options="allHeadingOptions"
    :title="getCurrentHeadingLabel()"
    :select-width="'100px'"
    @change="onHeadingChange"
  >
    <template #option="{ option }">
      <component
        :is="getHeadingTag(option.value)"
        class="heading-select-option-text"
        :class="getHeadingClass(option.value)"
      >
        {{ option.label }}
      </component>
    </template>
  </ToolbarButton>

  <!-- Ribbon 模式：使用 popover 类型 -->
  <ToolbarButton
    v-else-if="actualMode === 'ribbon'"
    type="popover"
    :title="getCurrentHeadingLabel()"
    :popover-width="300"
    popover-placement="bottom-start"
    popover-trigger="click"
    :popper-style="{
      padding: '8px',
      backgroundColor: 'var(--editor-color-white)',
    }"
  >
    <div class="heading-button-content">
      <div
        class="style-block"
        :class="{ active: currentHeading === 'paragraph' }"
        @click.stop="onHeadingChange('paragraph')"
      >
        <p class="style-text paragraph-style">正文</p>
      </div>
      <div
        class="style-block"
        :class="{ active: currentHeading === 'heading-1' }"
        @click.stop="onHeadingChange('heading-1')"
      >
        <h1 class="style-text heading-h1">标题 1</h1>
      </div>
      <span class="heading-dropdown-arrow">
        <i class="i-ri-arrow-down-s-line"></i>
      </span>
    </div>

    <template #popover>
      <div class="heading-popover-content">
        <div class="heading-grid">
          <div
            v-for="option in allHeadingOptions"
            :key="option.value"
            class="heading-option"
            :class="{ active: option.value === currentHeading }"
            @click="onHeadingChange(option.value)"
          >
            <component
              :is="getHeadingTag(option.value)"
              class="heading-option-text"
              :class="getHeadingClass(option.value)"
            >
              {{ option.label }}
            </component>
          </div>
        </div>
      </div>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, computed, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import type { EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { TOOLBAR_MODE_KEY } from "../../../toolbar/src/constants";
import type { ToolbarMode } from "../../../toolbar/src/types";
import { defaultDicts } from "../../../../config/constants";

const props = defineProps<{
  mode?: ToolbarMode; // 向后兼容，但推荐使用注入的工具栏模式
}>();

defineOptions({
  name: "HeadingSelector",
});

// 注入编辑器实例和配置
const editor = inject<Ref<Editor>>("editor");
const editorProps = inject<EditorProps>("editorProps");

// 注入工具栏模式
const toolbarMode = inject<Ref<ToolbarMode> | ToolbarMode | null>(
  TOOLBAR_MODE_KEY,
  null
);

// 计算实际使用的模式（与工具栏模式保持一致）
const actualMode = computed<ToolbarMode>(() => {
  // 优先使用 props.mode（向后兼容）
  if (props.mode) {
    return props.mode;
  }

  // 如果提供了工具栏模式，直接使用工具栏模式
  if (toolbarMode) {
    const mode =
      typeof toolbarMode === "object" && "value" in toolbarMode
        ? toolbarMode.value
        : toolbarMode;
    return mode;
  }

  // 默认返回 simple
  return "simple";
});

// 定义标题选项类型
interface HeadingOption {
  label: string;
  value: string;
  disabled?: boolean;
}

// 所有标题选项（包括正文）- 从 editorProps.dicts.headings 获取，如果没有则使用默认值
const allHeadingOptions = computed<HeadingOption[]>(() => {
  const headings = editorProps?.dicts?.headings || defaultDicts.headings || [];
  const locale = editorProps?.locale || "zh-CN";
  return headings.map((item: any) => {
    // 处理国际化标签，根据 locale 选择对应的语言
    let label: string;
    if (typeof item.label === "string") {
      label = item.label;
    } else if (typeof item.label === "object") {
      label =
        (locale === "zh-CN" ? item.label?.zh_CN : item.label?.en_US) ||
        item.label?.zh_CN ||
        item.label?.en_US ||
        item.value;
    } else {
      label = item.value;
    }
    return {
      label,
      value: item.value,
    };
  });
});

// 计算当前标题级别
const currentHeading = computed(() => {
  if (!editor?.value) return "paragraph";

  if (editor.value.isActive("paragraph")) {
    return "paragraph";
  }

  for (let i = 1; i <= 6; i++) {
    if (
      editor.value.isActive("heading", { level: i as 1 | 2 | 3 | 4 | 5 | 6 })
    ) {
      return `heading-${i}`;
    }
  }

  return "paragraph";
});

// 获取当前标题标签文本
const getCurrentHeadingLabel = () => {
  if (currentHeading.value === "paragraph") {
    const paragraphOption = allHeadingOptions.value.find(
      (opt) => opt.value === "paragraph"
    );
    return paragraphOption?.label || "正文";
  }
  const option = allHeadingOptions.value.find(
    (opt) => opt.value === currentHeading.value
  );
  return option?.label || "标题 1";
};

// 标题变化处理
const onHeadingChange = (value: string) => {
  if (value === "paragraph") {
    editor?.value?.chain().focus().setParagraph().run();
  } else if (value.startsWith("heading-")) {
    const level = parseInt(value.split("-")[1]) as 1 | 2 | 3 | 4 | 5 | 6;
    editor?.value?.chain().focus().setHeading({ level }).run();
  }
};

// 获取标题HTML标签
const getHeadingTag = (value: string) => {
  switch (value) {
    case "paragraph":
      return "p";
    case "heading-1":
      return "h1";
    case "heading-2":
      return "h2";
    case "heading-3":
      return "h3";
    case "heading-4":
      return "h4";
    case "heading-5":
      return "h5";
    case "heading-6":
      return "h6";
    default:
      return "p";
  }
};

// 获取标题样式类
const getHeadingClass = (value: string) => {
  switch (value) {
    case "paragraph":
      return "heading-paragraph";
    case "heading-1":
      return "heading-h1";
    case "heading-2":
      return "heading-h2";
    case "heading-3":
      return "heading-h3";
    case "heading-4":
      return "heading-h4";
    case "heading-5":
      return "heading-h5";
    case "heading-6":
      return "heading-h6";
    default:
      return "heading-paragraph";
  }
};
</script>

<style scoped>
/* 按钮内容样式 */
.heading-button-content {
  display: flex;
  align-items: center;
  background: var(--editor-button-hover-background);
  border-radius: var(--editor-radius-medium);
  padding: 4px;
  gap: 4px;
}

/* 样式方块 */
.style-block {
  background: var(--editor-color-white);
  border-radius: var(--editor-radius);
  padding: 0 2px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.style-block:hover {
  border-color: var(--editor-primary-color);
  background: var(--editor-color-white);
}

.style-block.active {
  border-color: var(--editor-primary-color);
  background: var(--editor-color-white);
}

/* 样式文本 */
.style-text {
  margin: 0;
  padding: 0;
  font-weight: 500;
  line-height: 1;
  text-align: center;
}

/* 下拉箭头 */
.heading-dropdown-arrow {
  background: transparent;
  border-radius: var(--editor-radius);
  cursor: pointer;
  transition: all 0.2s ease;
  height: auto;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  line-height: 1;
  color: var(--editor-text-color, #333);
  flex-shrink: 0;
}

.heading-dropdown-arrow:hover {
  background: var(--editor-button-hover-background);
}

.heading-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 2px;
}

.heading-option {
  background: white;
  border-radius: 4px;
  padding: 0 2px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid var(--editor-border-color);
  width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin: 2px 0;
}

.heading-option:hover {
  background: var(--editor-color-white);
  border-color: var(--editor-primary-color);
}

.heading-option.active {
  border-color: var(--editor-primary-color);
  background: var(--editor-content-node-selected-background);
}

.heading-option-text {
  margin: 0;
  padding: 0;
  font-weight: 500;
  line-height: 1;
  font-size: 12px;
}

/* 各级标题的样式 */
.paragraph-style {
  font-size: 14px;
  color: #333;
  font-weight: 400;
}

.heading-paragraph {
  font-size: 14px;
  color: #333;
  font-weight: 400;
}

.heading-h1 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.heading-h2 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.heading-h3 {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.heading-h4 {
  font-size: 13px;
  font-weight: 600;
  color: #333;
}

.heading-h5 {
  font-size: 12px;
  font-weight: 600;
  color: #333;
}

.heading-h6 {
  font-size: 11px;
  font-weight: 600;
  color: #666;
}

.heading-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.heading-subtitle {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.heading-subtle-emphasis {
  font-size: 14px;
  font-weight: 400;
  color: #666;
  font-style: italic;
}

.heading-emphasis {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.heading-strong-emphasis {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.heading-key-point {
  font-size: 14px;
  font-weight: 500;
  color: #1890ff;
}

.heading-quote {
  font-size: 14px;
  font-weight: 400;
  color: #666;
  font-style: italic;
}

.heading-strong-quote {
  font-size: 14px;
  font-weight: 500;
  color: #666;
  font-style: italic;
}

.heading-subtle-reference {
  font-size: 13px;
  font-weight: 400;
  color: #999;
}

.heading-strong-reference {
  font-size: 13px;
  font-weight: 500;
  color: #999;
}

.heading-book-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
}

.heading-list-style {
  font-size: 14px;
  font-weight: 400;
  color: #333;
}

/* Select 模式下的选项样式 */
.heading-select-option {
  margin: 0;
  padding: 0;
  font-weight: 500;
  line-height: 1.2;
  font-size: 14px;
}

.heading-select-option-text {
  margin: 0;
  padding: 0;
  font-weight: 500;
  line-height: 1.2;
}

.heading-select-option-text.heading-paragraph {
  font-size: 14px;
  color: #333;
  font-weight: 400;
}

.heading-select-option-text.heading-h1 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.heading-select-option-text.heading-h2 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.heading-select-option-text.heading-h3 {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.heading-select-option-text.heading-h4 {
  font-size: 13px;
  font-weight: 600;
  color: #333;
}

.heading-select-option-text.heading-h5 {
  font-size: 12px;
  font-weight: 600;
  color: #333;
}

.heading-select-option-text.heading-h6 {
  font-size: 11px;
  font-weight: 600;
  color: #666;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .heading-grid {
    grid-template-columns: repeat(4, 1fr);
    width: 256px; /* 4列 * 64px (60px + 4px gap) */
  }

  .style-block {
    width: 50px;
    height: 32px;
    padding: 0 2px;
  }

  .heading-dropdown-arrow {
    font-size: 14px;
  }

  .heading-option {
    width: 50px;
    height: 32px;
    padding: 0 2px;
  }

  .heading-option-text {
    font-size: 11px;
  }

  .heading-select-option {
    font-size: 12px;
  }
}
</style>
